package com.beamfield.controller.manage.operator;

import com.beamfield.common.ApiResult;
import com.beamfield.common.CommonUtils;
import com.beamfield.common.ImportExcelUtil;
import com.beamfield.common.PageResult;
import com.beamfield.controller.common.BaseController;
import com.beamfield.enums.HttpResultEnum;
import com.beamfield.model.*;
import com.beamfield.modelVo.TrainDetailsVo;
import com.beamfield.modelVo.TrainVo;
import com.beamfield.service.manage.operator.ManagerInfoService;
import com.beamfield.service.manage.operator.TrainService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 培训管理
 */
@Controller
@RequestMapping("/cms/operator/train")
public class TrainController extends BaseController{

    private final TrainService trainService;

    private final ManagerInfoService managerInfoService;

    @Value("${session.beam}")
    private String beam;

    @Value("${session.user}")
    private String user;

    @Autowired
    public TrainController(TrainService trainService, ManagerInfoService managerInfoService) {
        this.trainService = trainService;
        this.managerInfoService = managerInfoService;
    }

    /**
     *
     * @return 培训页面
     */
    @RequestMapping(value = "/index",method =RequestMethod.GET)
    public ModelAndView train(){
        return new ModelAndView();
    }

    /**
     *
     * @return 返回培训人员页面
     */
    @RequestMapping(value = "/details",method =RequestMethod.GET)
    public ModelAndView details(){
        return new ModelAndView();
    }

    /**
     *
     * @return 返回新增培训页面
     */
    @RequestMapping(value = "/add",method =RequestMethod.GET)
    public ModelAndView add(){
        return new ModelAndView();
    }

    /**
     * 获取培训数据
     * @param session
     * @param request
     * @return
     */
    @RequestMapping(value = "/readTrainData",method = RequestMethod.GET)
    @ResponseBody
    public PageResult readTrainData(HttpSession session, HttpServletRequest request){
        long beamId = (long) session.getAttribute(beam);
        String offset = request.getParameter("offset");
        String limit = request.getParameter("limit");
        //培训日期
        String trainDate = request.getParameter("trainDate");
        //组织部门
        String department = request.getParameter("department");
        String trainId = request.getParameter("trainId");
        String type = request.getParameter("type");
        if(StringUtils.isNotEmpty(type)){
            if("manager".equals(type)){
                type = "1";
            }else if ("special".equals(type)){
                type = "2";
            }else if ("normal".equals(type)){
                type = "3";
            }else{
                type = null;
            }
        }
        List<TrainVo> trainVoList = trainService.getTrainByBeamId(String.valueOf(beamId), offset, limit, trainDate, department, trainId, type);
        long total = trainService.countByBeamId(String.valueOf(beamId), trainDate, department,trainId, type);
        return new PageResult(total, Long.parseLong(offset), trainVoList);
    }
    /**
     * 获取培训人员数据
     * @param session
     * @param request
     * @return
     */
    @RequestMapping(value = "/readManagerTrainData", method = RequestMethod.GET)
    @ResponseBody
    public PageResult readManagerTrainData(HttpSession session, HttpServletRequest request){
        String offset = request.getParameter("offset");
        String trainId = request.getParameter("trainId");
        String limit = request.getParameter("limit");
        String operatorName = request.getParameter("operatorName");
        String workDepartment = request.getParameter("workDepartment");
        List<TrainDetailsVo> trainDetailsVoList = trainService.getTrainDetailsByTrainId(trainId, offset, limit, operatorName, workDepartment);
        long total = trainService.countDetailsByTrainId(trainId, operatorName, workDepartment);
        return new PageResult(total, Long.parseLong(offset), trainDetailsVoList);
    }
    /**
     * 新增一条培训人员信息
     * @param request
     * @param session
     * @return
     */
    @RequestMapping(value = "/addManagerTrain",method = RequestMethod.POST)
    @ResponseBody
    public ApiResult addManagerTrain(HttpServletRequest request, HttpSession session){
        long userId = (long) session.getAttribute(this.user);
        long beamId = (long) session.getAttribute(this.beam);
        ApiResult apiResult = new ApiResult(HttpResultEnum.MIS_PARAM.getCode(),HttpResultEnum.MIS_PARAM.getMessage());
        String trainId = request.getParameter("trainId");
        String ecode = request.getParameter("ecode");
        if(StringUtils.isEmpty(trainId)){
            return apiResult;
        }
        if(StringUtils.isEmpty(ecode)){
            return apiResult;
        }
        int result = 0;
        try{
            result = trainService.saveManagerTrain(userId, trainId, ecode, beamId);
            if (result==2){
                apiResult.setCode(HttpResultEnum.EXCEPTION.getCode());
                apiResult.setMessage("新增的培训人员已存在");
                return apiResult;
            }
        }catch (Exception e){
            e.printStackTrace();
            apiResult.setCode(HttpResultEnum.EXCEPTION.getCode());
            apiResult.setMessage(HttpResultEnum.EXCEPTION.getMessage());
        }
        if(result == 1){
            apiResult.setCode(HttpResultEnum.SUCCESS.getCode());
            apiResult.setMessage("新增培训人员成功");
        }
        return apiResult;
    }

    /**
     * 录入成绩
     * @param session
     * @param request
     * @return
     */
    @RequestMapping(value = "/entryScore", method = RequestMethod.POST)
    @ResponseBody
    public ApiResult entryScore(HttpSession session, HttpServletRequest request){
        ApiResult apiResult = new ApiResult();
        apiResult.setMessage("录入成绩失败");
        long userId = (long) session.getAttribute(this.user);
        String managerTrainId = request.getParameter("managerTrainId");
        String score = request.getParameter("score");
        ManagerTrain managerTrain = new ManagerTrain();
        managerTrain.setManager_train_id(Long.parseLong(managerTrainId));
        managerTrain.setAchievement(score);
        managerTrain.setUpdatetime(new Date());
        managerTrain.setUpdater(userId);
        int result = 0;
        try {
            result = trainService.updateManagerTrain(managerTrain);
        }catch (Exception e){
            e.printStackTrace();
        }
        if(result == 1){
            apiResult.setMessage("录入成绩成功");
        }
        return apiResult;
    }

    /**
     * 删除培训人员数据
     * @param request
     * @return
     */
    @RequestMapping(value = "/delManagerTrain", method = RequestMethod.POST)
    @ResponseBody
    public ApiResult delManagerTrain(HttpServletRequest request,HttpSession session){
        long userId = (long) session.getAttribute(this.user);
        ApiResult apiResult = new ApiResult(HttpResultEnum.MIS_PARAM.getCode(),"删除记录失败");
        String managerTrainId = request.getParameter("managerTrainId");
        int result = 0;
        try {
            result = trainService.delDetailsByMId(Arrays.asList(managerTrainId),userId);
        }catch (Exception e){
            e.printStackTrace();
        }
        if(result == 1){
            apiResult.setMessage("删除记录成功");
            apiResult.setCode(HttpResultEnum.SUCCESS.getCode());
        }
        return apiResult;
    }

    /**
     * 取消培训
     * @param request
     * @return
     */
    @RequestMapping(value = "/delTrain", method = RequestMethod.POST)
    @ResponseBody
    public ApiResult delTrain(HttpServletRequest request, HttpSession session){
        long userId = (long) session.getAttribute(this.user);
        ApiResult apiResult = new ApiResult(HttpResultEnum.MIS_PARAM.getCode(),"删除记录失败");
        String trainId = request.getParameter("trainId");
        int result = 0;
        try{
            result = trainService.delTrainByTrainId(Arrays.asList(trainId),userId);
        }catch (Exception e){
            e.printStackTrace();
        }
        if(result == 1){
            apiResult.setMessage("删除记录成功");
            apiResult.setCode(HttpResultEnum.SUCCESS.getCode());
        }
        return apiResult;
    }

    /**
     * 导入培训人员数Excel
     * @param multipartFile
     * @return
     */
    @RequestMapping(value = "/importTrainers", method = RequestMethod.POST)
    @ResponseBody
    public ApiResult importTrainers(@RequestParam(value = "trainExcel") MultipartFile multipartFile){
        ApiResult apiResult = new ApiResult();
        apiResult.setMessage("上传失败");
        ImportExcelUtil importExcelUtil = new ImportExcelUtil();
        List<List<Object>> trainList = null;
        try {
            trainList = importExcelUtil.getBankListByExcel(multipartFile.getInputStream(), multipartFile.getOriginalFilename());
        }catch (Exception e){
            e.printStackTrace();
            return apiResult;
        }
        long commeFileId = super.saveFile((CommonsMultipartFile) multipartFile);
        if(trainList.stream().anyMatch(v -> StringUtils.isEmpty(String.valueOf(v.get(1))))){
            return new ApiResult(HttpResultEnum.EXCEPTION.getCode(), "身份证不能为空，请检查");
        }
        if(trainList.stream().map(v -> String.valueOf(v.get(1))).collect(Collectors.toSet()).size() != trainList.size()){
            return new ApiResult(HttpResultEnum.EXCEPTION.getCode(), "存在相同的身份证数据，请检查");
        }
        List<Map<String,String>> o = new ArrayList<>();
        if( trainList != null && !trainList.isEmpty()){
            for(int i=0,l=trainList.size(); i<l; i++){
                List list = trainList.get(i);
                Map<String,String> map = new HashMap<>();
                map.put("manager_train_id",String.valueOf(i));
                map.put("name",String.valueOf(list.get(0)));
                String identity = String.valueOf(list.get(1)).trim();
                map.put("identity", identity);
                map.put("workdept",String.valueOf(list.get(2)));
                map.put("presasg",String.valueOf(list.get(3)));
                o.add(map);
            }
        }else{
            return new ApiResult(HttpResultEnum.EXCEPTION.getCode(), "未读取到数据");
        }
        Map<String,Object> resultMap = new HashMap<>();
        resultMap.put("managerTrain",o);
        resultMap.put("commFileId",commeFileId);
        apiResult.setResult(resultMap);
        apiResult.setMessage("上传成功");
        return apiResult;
    }

    /**
     * 保存培训信息和培训人员数据
     * @param trainInfo 培训信息
     * @param trainDate 培训日期
     * @param identityData 培训人员身份证信息
     * @param commFileId 培训ExcelId
     * @param session
     * @return
     */
    @RequestMapping(value = "/doSave")
    @ResponseBody
    public ApiResult save(String achievementstr,String train_time,TrainInfo trainInfo,String trainDate, String identityData, String commFileId,String endtime,  HttpSession session){
        ApiResult apiResult = new ApiResult();
        long userId = (long) session.getAttribute(this.user);
        long beamId = (long) session.getAttribute(beam);
        String[] identitys = identityData.split(",");
        String[] achievements=achievementstr.split(",");
        List<String> encodes = new ArrayList<>();
        if(identitys.length != 0) {
            Set<String> set = new HashSet<String>();
            for (int i = 0; i < identitys.length; i++) {
                String identity = identitys[i];
                if(StringUtils.isBlank(identity)){
                    continue;
                }
                Object o = managerInfoService.getOperatorInfoByIdentity(identity);
                if (o == null) {
                    apiResult.setMessage("未找到身份证为： " + identity + " 的人员，请先新增人员信息");
                    apiResult.setCode(HttpResultEnum.MIS_PARAM.getCode());
                    return apiResult;
                }
                String encode = "";
                if (o instanceof ManagerInfo) {
                    encode = ((ManagerInfo) o).getEcode();
                }
                if (o instanceof NormalOperator) {
                    encode = ((NormalOperator) o).getEcode();
                }
                if (o instanceof SpecialOperator) {
                    encode = ((SpecialOperator) o).getEcode();
                }
                set.add(encode);
                encodes.add(encode);

            }
//            if (set.size() != identitys.length) {
//                apiResult.setMessage("培训人员有重复，请检查");
//                apiResult.setCode(HttpResultEnum.MIS_PARAM.getCode());
//                return apiResult;
//            }
        }
        if(StringUtils.isNotEmpty(commFileId)) {
            trainInfo.setJoinperson(Long.parseLong(commFileId));
        }

        trainInfo.setTraintime(CommonUtils.getDateFormat(trainDate,"yyyy-MM-dd"));
        if (!StringUtils.isEmpty(endtime)) {
            trainInfo.setEnddate(CommonUtils.getDateFormat(endtime, "yyyy-MM-dd"));
        }
        try {
            trainService.savaTrainAndTrainDetail(trainInfo,encodes,beamId,userId,train_time,achievements);
        }catch (Exception e){
            e.printStackTrace();
            apiResult.setCode(HttpResultEnum.EXCEPTION.getCode());
            apiResult.setMessage(HttpResultEnum.EXCEPTION.getMessage());
        }
        apiResult.setCode(HttpResultEnum.SUCCESS.getCode());
        apiResult.setMessage("新增成功");
        return apiResult;
    }

    /**
     * 更新培训信息和培训人员信息
     * @param trainInfo
     * @param session
     * @return
     */
    @RequestMapping(value = "/update")
    @ResponseBody
    public ApiResult update(String achievementstr,String train_time,TrainInfo trainInfo,String trainDate, String identityData, String commFileId,String endtime, HttpSession session){
        ApiResult apiResult = new ApiResult(HttpResultEnum.MIS_PARAM.getCode(),HttpResultEnum.MIS_PARAM.getCode());
        long userId = (long) session.getAttribute(this.user);
        long beamId = (long) session.getAttribute(beam);
        List<String> encodes = new ArrayList<>();
        String[] achievements=achievementstr.split(",");
        trainInfo.setUpdater(userId);
        trainInfo.setUpdatetime(new Date());
        if(!StringUtils.isEmpty(commFileId)){
            String[] identitys = identityData.split(",");
            Set<String> set=new HashSet<String>();
            for(String identity : identitys) {
                Object o = managerInfoService.getOperatorInfoByIdentity(identity);
                if (o == null) {
                    apiResult.setMessage("未找到身份证为： " + identity + " 的人员，请先新增人员信息");
                    apiResult.setCode(HttpResultEnum.MIS_PARAM.getCode());
                    return apiResult;
                }
                String encode = "";
                if (o instanceof ManagerInfo) {
                    encode = ((ManagerInfo) o).getEcode();
                }
                if (o instanceof NormalOperator) {
                    encode = ((NormalOperator) o).getEcode();
                }
                if (o instanceof SpecialOperator) {
                    encode = ((SpecialOperator) o).getEcode();
                }
                encodes.add(encode);
                set.add(encode);
            }
            if (set.size() != identitys.length) {
                apiResult.setMessage("培训人员有重复，请检查");
                apiResult.setCode(HttpResultEnum.MIS_PARAM.getCode());
                return apiResult;
            }

        }
        if (!StringUtils.isEmpty(endtime)) {
            trainInfo.setEnddate(CommonUtils.getDateFormat(endtime, "yyyy-MM-dd"));
        }
        int result = 0;
        try{
            result = trainService.update(trainInfo, trainDate, encodes, commFileId, beamId,train_time,achievements);
        }catch (Exception e){
            e.printStackTrace();
        }
        if(result == 1){
            apiResult.setCode(HttpResultEnum.SUCCESS.getCode());
            apiResult.setMessage("更新成功");
        }
        return apiResult;
    }

    /**
     * 导出培训信息
     * @param request
     * @return
     */
    @RequestMapping(value = "/exportTrain")
    @ResponseBody
    public ApiResult exportTrain(HttpServletRequest request, HttpServletResponse response){
        String trainId = request.getParameter("trainId");
        Long beamId = super.getBeamId(request);
        if(StringUtils.isEmpty(trainId)){
            return new ApiResult(HttpResultEnum.MIS_PARAM.getCode(),HttpResultEnum.MIS_PARAM.getMessage());
        }
        return trainService.exportTrain(beamId, trainId, response);
    }
}
